import { Body, Controller, Get, Post, UseGuards, Headers } from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { CurUser } from 'src/decorators/user.decorator';
import { AuthGuard } from '../auth/auth.guard';
import { CreateUserDto } from './dto/create.user.dto';
import { UserBindRoleDto } from './dto/user.bind.role.dto';
import { UserEntity } from './entities/user.entity';
import { UserService } from './user.service';

@ApiTags('后台管理系统-用户管理')
@ApiBearerAuth()
@UseGuards(AuthGuard)
@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) {}

  @ApiOperation({ summary: '获取用户信息' })
  @Get()
  async getUserInfo(@Headers() header: any) {
    console.log('2022-09-24 10:56:41', 111);
    return await this.userService.getUser(header);
  }

  @ApiOperation({ summary: '创建用户' })
  @Post()
  async createUser(@Body() createUserDto: CreateUserDto): Promise<string> {
    return await this.userService.createUser(createUserDto);
  }

  /**
   * @Author: laotongshu
   * @Date: 2022-10-11 14:45:45
   * @LastEditors: laotongshu
   * @Description: 获取当前用户权限信息
   * @param {Object} {}
   * @return {*}
   */
  @ApiOperation({ summary: '获取当前用户权限信息' })
  @Get('role')
  public async permissions(@CurUser() user: UserEntity) {
    const roleId = user.userRoles?.[0]?.roleId;
    // 根据角色ID获取资源
    const role = this.userService.resourceById(roleId);
    // if (user.isAdmin) {
    //   // 获取所有权限
    //   // this.roleService.list()
    //   role = new RoleEntity();
    //   role.name = 'SYSTEM';
    //   // role.roleAcls = await this.aclService.findAll();
    // }
    return role || {};
  }

  /**
   * @Author: laotongshu
   * @Date: 2022-10-11 14:53:37
   * @LastEditors: laotongshu
   * @Description: 给用户绑定角色
   * @param {Object} {}
   * @return {*}
   */
  @ApiOperation({ summary: '给用户绑定角色' })
  @Post('bind/role')
  async bindRole(@Body() roleDto: UserBindRoleDto, @CurUser() user: UserEntity) {
    console.log('2022-10-12 09:46:02', user);
    if (user.isSuper !== 1) {
      return '不是管理员不能绑定角色';
    }
    return this.userService.bindRole(roleDto.userId, roleDto.roleId);
  }
}
